<template>
  <div class="container">
    <h3 class="t_a mb_20" v-if="orderNo">修理订单{{ orderNo }} 流转详情</h3>
    <div class="mt_20 mb_20" v-if="totalSteps">
      <steps
        :currentStep="currentStep"
        :totalSteps="totalSteps"
        :stepsData="stepsData"
        @clickSteps="clickSteps"
      />
    </div>
    <div style="margin-bottom: 10px">
      <el-input v-model="inputSpecs" placeholder="请输入规格" />
      <el-input
        v-model="inputNumber"
        placeholder="请输入模具编号"
        style="margin-left: 10px"
      />
      <el-button @click="resetInput" style="margin-left: 10px">重置</el-button>
      <el-button @click="inputSearch" type="primary">查询</el-button>
    </div>
    <el-table v-loading="isLoading" :data="tableData" border class="table">
      <el-table-column
        prop="specs"
        label="规格"
        align="center"
      ></el-table-column>

      <el-table-column prop="num" label="数量" align="center"></el-table-column>
      <el-table-column
        prop="staff_name"
        label="员工"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="production"
        label="工艺"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="200px">
        <template slot-scope="scope">
          <el-button type="text" @click="showBackDialog(scope.$index)"
            >回退</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="回退" :visible.sync="backDialog" width="400px">
      <el-form>
        <el-form-item label="规格" prop="backSpecs" label-width="70px">
          <el-input v-model="backSpecs" style="width: 215px" disabled="true" />
        </el-form-item>
        <el-form-item label="员工" label-width="70px" prop="backStaffName">
          <el-input
            v-model="backStaffName"
            style="width: 215px"
            disabled="true"
          />
        </el-form-item>
        <el-form-item label="当前工艺" prop="nowProduction">
          <el-input
            v-model="nowProduction"
            style="width: 215px"
            disabled="true"
          />
        </el-form-item>
        <el-form-item label="完成数量" prop="backNum">
          <el-input v-model="backNum" style="width: 215px" disabled="true" />
        </el-form-item>
        <el-form-item label="回退数量" prop="realBackNum">
          <el-input v-model="realBackNum" style="width: 215px" type="number" />
        </el-form-item>
      </el-form>
      <div v-if="nowProduction == '品管镜检' || nowProduction == '品管挪检'">
        <el-form-item label="回退工艺(多选)"></el-form-item>
        <el-checkbox-group
          style="margin-top: -10px"
          v-model="checkedProductions"
          @change="handleCheckedProductionsChange"
        >
          <el-checkbox
            v-for="production in backProductionList"
            :label="production"
            :key="production"
            :value="production"
            >{{ production }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
      <div v-else style="font-size: 20px">是否回退到上一工艺？</div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="backDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmBack()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="specTitle" :visible.sync="specDialog" width="90%">
      <div v-if="totalStepsSpec">
        <steps
          :currentStep="currentStepSpec"
          :totalSteps="totalStepsSpec"
          :stepsData="stepsDataSpec"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from "../../../api";
import steps from "./steps.vue";
import {
  ResponsibleDepartment,
  OrderRejectReason2,
  OrderRejectReason,
} from "../../common/enum";

export default {
  name: "flowDetail",
  components: {
    steps,
  },
  data() {
    return {
      inputSpecs: "",
      inputNumber: "",
      isLoading: false,
      tableData: [],
      tableData2: [],
      tableData3: [],
      dialogVisible: false,
      specDialog: false,
      replenishment: {
        angle: "",
        customer: "",
        checkPerson: "",
        checkPersonName: "",
        equipmentName: "",
        equipmentNumber: "",
        checkTime: "",
        createTime: "",
        dept: "",
        number: "",
        operator: "",
        operatorName: "",
        orderNo: "",
        production: "",
        reason: "",
        remark: "",
        specs: "",
        staffId: "",
        staffName: "",
        staffNo: "",
        status: "",
        useSpecs: "",
      },
      stepsDesc: [],
      rules: {
        reason: [{ required: true, message: "请输入原因", trigger: "change" }],
        dept: [
          { required: true, message: "请选择责任部门", trigger: "change" },
        ],
        useSpecs: [{ required: true, message: "请输入", trigger: "blur" }],
        angle: [{ required: true, message: "请填写", trigger: "blur" }],
      },
      rejectReason: [],
      depart: [],
      stepsData: [],
      currentStep: 0,
      totalSteps: 0,
      stepsDataSpec: [],
      currentStepSpec: 0,
      totalStepsSpec: 0,
      orderProduction: [],
      clickStep: 0,
      backDialog: false,
      selectedBackIndex: -1,
      specTitle: "",
      orderNo: "",
      nowProduction: "",
      backProduction: null,
      backSpecs: "",
      backNumber: "",
      backStaffName: "",
      backNum: "",
      realBackNum: null,
      backOrderNo: "",
      backProductionList: [],
      replenishmentParams: {},
      checkedProductions: [],
    };
  },
  created() {
    // this.rejectReason = OrderRejectReason;
    this.depart = ResponsibleDepartment;
  },
  mounted() {
    this.orderNo = this.$route.query.id;
    this.getData();
  },
  methods: {
    deptChange() {
      console.info(this.replenishment.dept);
      if ("材质" == this.replenishment.dept) {
        this.rejectReason = OrderRejectReason2;
      } else {
        this.rejectReason = OrderRejectReason;
      }
    },

    resetInput() {
      this.tableData = this.tableData2;
      this.inputSpecs = "";
      this.inputNumber = "";
    },
    inputSearch() {
      debugger;
      this.tableData3 = [];
      this.tableData = this.tableData2;
      if (this.inputSpecs == "" && this.inputNumber == "") {
        return;
      }

      // 只通过规格筛选
      if (this.inputSpecs != "" && this.inputNumber == "") {
        for (var item of this.tableData) {
          if (item.specs == this.inputSpecs) {
            this.tableData3.push(item);
          }
        }
        this.tableData = this.tableData3;
      }

      // 只通过模具编号筛选
      else if (this.inputSpecs == "" && this.inputNumber != "") {
        for (var item of this.tableData) {
          if (item.number == this.inputNumber) {
            this.tableData3.push(item);
            break;
          }
        }
        this.tableData = this.tableData3;
      }
      //通过规格和模具编号
      else if (this.inputSpecs != "" && this.inputNumber != "") {
        for (var item of this.tableData) {
          if (
            item.number == this.inputNumber &&
            item.specs == this.inputSpecs
          ) {
            this.tableData3.push(item);
          }
        }
        this.tableData = this.tableData3;
      }
    },

    handleCheckedProductionsChange() {
      console.info(this.checkedProductions);
      this.backProduction = this.checkedProductions.toString();
      console.info(this.backProduction);
    },

    getData() {
      api
        .orderProductionRecord({ orderNo: this.orderNo })
        .then((res) => {
          if (res.code === 200) {
            this.stepsData = [];
            for (let i = 0; i < res.data.length; i++) {
              const element = res.data[i];
              const time =
                element.startTime && element.endTime
                  ? element.startTime + "~" + element.endTime
                  : element.startTime && !element.endTime
                  ? element.startTime
                  : "";
              console.info(1);
              console.info(time);
              this.stepsDesc.push(time);
              if (element.status == "1") this.currentStep = i + 1;
              this.stepsData.push({
                label: element.production,
                orderNo: element.orderNo,
                desc: time,
                total: element.total,
                ngNum: element.ngNum,
                ngNumStr: element.ngNumStr,
                hasDone: element.hasDone,
                toBeCompleted: element.toBeCompleted,
                status: element.status,
              });
              // if (element.status == "2") this.currentStep = i + 1;
            }
            this.orderProduction = res.data;
            this.totalSteps = res.data.length;
            this.clickStep = this.currentStep - 1;
            if (this.clickStep < 0) this.clickStep = 0;
            this.getTableData(this.clickStep);
          }
        })
        .catch();
    },
    clickSteps(index) {
      this.clickStep = index - 1;
      this.getTableData(this.clickStep);
    },
    getTableData(step) {
      this.inputSpecs = "";
      this.inputNumber = "";
      console.info(this.orderProduction);
      console.info(step);
      if (this.orderProduction.length == 0) {
        return;
      }
      this.isLoading = true;
      api
        .orderItemProductionRecordForUpdate({
          orderNo: this.orderNo,
          production: this.orderProduction[step].production,
        })
        .then((res) => {
          if (res.code === 200) {
            console.info("查询结果", res.data);
            this.tableData = res.data;
            this.tableData2 = res.data;
            this.isLoading = false;
          }
        })
        .catch((this.isLoading = false));

      // 获取可以回退的工艺
      var flag = 1;
      this.backProductionList = [];

      console.info("可回退列表");
      console.info(this.backProductionList);
    },
    showDialog(row) {
      //查询申请人是谁
      /**
            如果row.staffId等于空 则需要查询上一工序是谁流转的
         */

      var staffId = row.staffId;
      var staffName = row.staffName;
      var staffNumber = row.staffNumber;
      console.info("1111" + row.staffId);
      if (row.staffId == null || row.staffId == "") {
        var index = 0;
        for (var i = 1; i <= this.stepsData.length; i++) {
          if (row.production == this.stepsData[i - 1].label) {
            index = i;
            console.info("1==" + i);
            var stepProduction = "";
            if (i == 1) {
              stepProduction = this.stepsData[i - 1].label;
            } else {
              stepProduction = this.stepsData[i - 2].label;
            }
          }
        }
      } else {
        this.replenishment = {
          number: row.number,
          orderNo: this.orderNo,
          production: row.production,
          roughSupplier: row.roughSupplier,
          staffNo: staffNumber,
          staffName: staffName,
          staffId: staffId,
          specs: row.specs,
        };
        this.dialogVisible = true;
      }
      this.replenishment = {
        number: row.number,
        orderNo: this.orderNo,
        production: row.production,
        roughSupplier: row.roughSupplier,
        staffNo: staffNumber,
        staffName: staffName,
        staffId: staffId,
        specs: row.specs,
      };
      this.dialogVisible = true;

      api
        .queryReplenishmentParams({ orderNo: this.orderNo, specs: row.specs })
        .then((res) => {
          console.info("补料参数");
          console.info(res.data);
          this.replenishmentParams = res.data;
        });

      console.info(this.replenishment);
    },
    showSpecDialog(row) {
      api
        .orderItemProductionInfo({
          orderNo: this.orderNo,
          number: row.number,
          specs: row.specs,
        })
        .then((res) => {
          if (res.code === 200) {
            this.stepsDataSpec = [];
            for (let i = 0; i < res.data.length; i++) {
              const element = res.data[i];
              const time =
                element.startTime && element.endTime
                  ? element.startTime + "~" + element.endTime
                  : element.startTime && !element.endTime
                  ? element.startTime
                  : "";
              this.stepsDataSpec.push({
                label: element.production,
                  orderNo: element.orderNo,
                desc: time,
                status: element.status,
              });
              if (element.status == "1") this.currentStepSpec = i + 1;
            }
            this.orderProduction = res.data;
            this.totalStepsSpec = res.data.length;
            this.specTitle = `订单编号【${this.orderNo} 】模板编号【${row.number}】`;
            this.specDialog = true;
          }
        })
        .catch();
    },
    confirmBack() {
      // 回退的数量不能大于完成的额数量

      if (parseInt(this.realBackNum) > parseInt(this.backNum)) {
        this.$message.info("回退数量不能大于" + this.backNum);
        return;
      }
      if (parseInt(this.realBackNum) == 0) {
        this.$message.info("回退数量不能为0");
        return;
      }

      if (this.nowProduction == "品管") {
        if (this.backProduction == null || this.backProduction == "") {
          this.$message.info("请先选择回退工艺");
          return;
        }
      }
      api
        .productionRecordBackForUpdate({
          num: this.realBackNum,
          staffName: this.backStaffName,
          orderNo: this.orderNo,
          specs: this.tableData[this.selectedBackIndex].specs,
          nowProduction: this.tableData[this.selectedBackIndex].production,
          backProduction: this.backProduction,
        })
        .then((res) => {
          if (res.code === 200) {
            this.$message.success("操作成功！");
            this.getTableData(this.clickStep);
            this.getData();
          }
          this.backDialog = false;
        });
    },
    showBackDialog(index) {
      this.selectedBackIndex = index;
      this.checkedProductions = [];
      this.backDialog = true;
      this.nowProduction = this.tableData[this.selectedBackIndex].production;
      this.backSpecs = this.tableData[this.selectedBackIndex].specs;
      this.backNum = this.tableData[this.selectedBackIndex].num;
      this.backOrderNo = this.tableData[this.selectedBackIndex].orderNo;
      this.backStaffName = this.tableData[this.selectedBackIndex].staff_name;

      api
        .getOrderProductions({
          orderNo: this.tableData[this.selectedBackIndex].orderNo,
          specs: this.tableData[this.selectedBackIndex].specs,
        })
        .then((res) => {
          if (res.code === 200) {
            // 不能选择超过其的工序
            console.info(" this.nowProduction", this.nowProduction);
            var tmep = [];
            var add = true;
            for (var i = 0; i < res.data.length; i++) {
              if (add) {
                tmep.push(res.data[i]);
              }
              console.info(res.data[i]);
              if (res.data[i] == this.nowProduction) {
                add = false;
              }
            }

            this.backProductionList = tmep;
          }
        })
        .catch();
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          api.replenishmentAdd(this.replenishment).then((res) => {
            if (res.code === 200) {
              this.dialogVisible = false;
              this.$message.success("操作成功！");
              this.getTableData(this.clickStep);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
.upload-demo {
  height: 32px;
  display: inline-block;
  margin-left: 10px;
}
.ruleForm {
  width: 400px;
}

.line {
  display: block;
  width: 600px;
}
.el-input {
  position: relative;
  font-size: 14px;
  display: inline-block;
  width: 178px !important;
}
.el-select > .el-input {
  display: block;
  width: 178px;
}

.el-select {
  display: inline-block;
  position: relative;
  width: 178px !important;
}
.line-left {
  display: inline-block !important;
  width: 300px;
}
.line-right {
  display: inline-block !important;
  width: 300px;
}

.el-select {
  display: inline-block;
  position: relative;
  width: 200px;
}

.class_title {
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 600;
  margin-left: 70%;
}
</style>

